<template>
  <div class="scenic-management-container">
    <div class="scenic-management-header">
      <div class="header-actions">
        <el-button type="primary" plain size="small" @click="goBack">
          <el-icon><Back /></el-icon> 返回首页
        </el-button>
      </div>
      <h1>保护区要素管理</h1>
      <p>管理青岛自然保护区地理要素信息</p>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧地图区域 -->
      <el-col :span="16">
        <el-card class="map-card">
          <div id="scenicMapView" class="map-container"></div>

          <!-- 状态指示器 - 添加模式 -->
          <div class="status-indicator" v-if="isAddingMode">
            <div class="pulse-dot"></div>
            <span>请在地图上绘制保护区边界</span>
            <el-button size="small" @click="cancelAddingMode" class="cancel-btn">取消</el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧功能区域 -->
      <el-col :span="8">
        <!-- 景区选择 -->
        <el-card class="area-select-card">
          <template #header>
            <div class="card-header">
              <span>区域选择</span>
            </div>
          </template>

          <div class="area-tabs">
            <el-tabs v-model="activeArea" @tab-click="handleAreaChange">
              <el-tab-pane label="胶南灵山岛保护区" name="erdihu"></el-tab-pane>
            <el-tab-pane label="大公岛保护区" name="yunmen"></el-tab-pane>
            <el-tab-pane label="大泽山保护区" name="bailang"></el-tab-pane>
            <el-tab-pane label="崂山保护区" name="xiashan"></el-tab-pane>
            <el-tab-pane label="胶州艾山保护区" name="binhai"></el-tab-pane>
            <el-tab-pane label="马山保护区" name="mihe"></el-tab-pane>
            </el-tabs>
          </div>
        </el-card>

        <!-- 操作面板 -->
        <el-card class="action-card">
          <template #header>
            <div class="card-header">
              <span>操作面板</span>
            </div>
          </template>

          <div class="action-buttons">
            <el-button type="primary" @click="startAddingMode">
              <el-icon><Plus /></el-icon>添加保护区
            </el-button>
            <el-button type="warning" :disabled="!selectedFeatureId" @click="openEditForm">
              <el-icon><Edit /></el-icon>编辑保护区
            </el-button>
            <el-button type="danger" :disabled="!selectedFeatureId" @click="deleteFeature">
              <el-icon><Delete /></el-icon>删除保护区
            </el-button>
          </div>

          <div v-if="selectedFeatureId" class="selected-feature-info">
            <h3>已选择: {{ selectedFeatureName }}</h3>
            <p v-if="selectedFeatureType">类型: {{ selectedFeatureType }}</p>
          </div>
        </el-card>

        <!-- 保护区列表 -->
        <el-card class="feature-list-card">
          <template #header>
            <div class="card-header">
              <span>保护区列表</span>
              <el-input
                v-model="searchQuery"
                placeholder="搜索保护区名称"
                clearable
                class="search-input"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </template>

          <el-table
            :data="tableData"
            style="width: 100%"
            v-loading="loading"
            @row-click="handleRowClick"
          >
            <el-table-column prop="attributes.FID" label="ID" width="80" />
            <el-table-column prop="attributes.Name" label="保护区名称" />
            <el-table-column prop="attributes.AreaType" label="区域类型" />
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" type="primary" @click.stop="viewFeatureDetails(scope.row)">
                  查看
                </el-button>
                <el-button size="small" type="warning" @click.stop="editFeature(scope.row)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 添加/编辑表单抽屉 -->
  <el-drawer
    v-model="showFormDrawer"
    :title="isEditing ? '编辑保护区' : '添加保护区'"
    direction="rtl"
    size="500px"
    :before-close="handleFormClose"
  >
    <el-form :model="formData" label-position="top" class="feature-form" ref="formRef">
      <!-- 基本信息部分 -->
      <el-divider content-position="left">基本信息</el-divider>

      <el-form-item
        label="保护区名称"
        prop="Name"
        :rules="[{ required: true, message: '请输入保护区名称', trigger: 'blur' }]"
      >
        <el-input v-model="formData.Name" placeholder="请输入保护区名称"></el-input>
      </el-form-item>

      <el-form-item
        label="区域类型"
        prop="AreaType"
        :rules="[{ required: true, message: '请选择区域类型', trigger: 'change' }]"
      >
        <el-select v-model="formData.AreaType" placeholder="请选择区域类型" style="width: 100%">
          <el-option label="保护区浏览区" value="保护区浏览区"></el-option>
          <el-option label="缓冲区" value="缓冲区"></el-option>
          <el-option label="自然保护区" value="自然保护区"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="保护区描述" prop="Description">
        <el-input
          v-model="formData.Description"
          type="textarea"
          rows="4"
          placeholder="请输入保护区描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="状态" prop="Status">
        <el-select v-model="formData.Status" placeholder="请选择状态" style="width: 100%">
          <el-option label="正常开放" value="正常开放"></el-option>
          <el-option label="维护中" value="维护中"></el-option>
          <el-option label="暂停开放" value="暂停开放"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="价格信息" prop="Price" v-if="formData.AreaType === '保护区浏览区'">
        <el-input v-model="formData.Price" placeholder="请输入价格信息，为空表示免费">
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="保护区图片" prop="PhotoBase64">
        <!-- 如果有照片数据，显示照片 -->
        <div v-if="formData.PhotoBase64 && formData.PhotoBase64.length > 0" class="existing-photo">
          <el-image
            style="width: 100%; max-height: 200px"
            :src="formData.PhotoBase64"
            fit="contain"
          ></el-image>
          <el-button type="danger" size="small" @click="handlePhotoRemove" class="remove-photo-btn">
            删除照片
          </el-button>
        </div>
        <!-- 如果没有照片数据，显示上传组件 -->
        <el-upload
          v-else
          class="upload-demo"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :limit="1"
          :on-change="handlePhotoChange"
          :on-remove="handlePhotoRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <!-- 隐藏的所属区域字段 -->
      <input type="hidden" v-model="formData.OwnerArea" />

      <div class="form-actions">
        <el-button @click="showFormDrawer = false">取消</el-button>
        <el-button type="primary" @click="saveFeature">保存</el-button>
      </div>
    </el-form>
  </el-drawer>

  <!-- 详情抽屉 -->
  <el-drawer v-model="showDetailsDrawer" title="保护区详情" direction="rtl" size="500px">
    <div v-if="currentFeature" class="feature-details">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="保护区名称">
          {{ currentFeature.attributes.Name || '无' }}
        </el-descriptions-item>

        <el-descriptions-item label="区域类型">
          <el-tag :type="getTypeTagType(currentFeature.attributes.AreaType)">
            {{ currentFeature.attributes.AreaType || '无' }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="保护区描述">
          {{ currentFeature.attributes.Description || '无描述信息' }}
        </el-descriptions-item>

        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentFeature.attributes.Status)">
            {{ currentFeature.attributes.Status || '未知' }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="价格信息" v-if="currentFeature.attributes.AreaType === '保护区浏览区'">
          {{ currentFeature.attributes.Price ? currentFeature.attributes.Price + '元' : '免费' }}
        </el-descriptions-item>

        <el-descriptions-item label="保护区图片" v-if="currentFeature.attributes.PhotoBase64">
          <el-image
            style="width: 100%; max-height: 300px"
            :src="currentFeature.attributes.PhotoBase64"
            fit="contain"
          ></el-image>
        </el-descriptions-item>
      </el-descriptions>

      <div class="details-actions">
        <el-button type="primary" @click="editFeature(currentFeature)">
          <el-icon><Edit /></el-icon> 编辑保护区
        </el-button>
      </div>
    </div>
    <div v-else class="no-feature-selected">
      <el-empty description="没有选中保护区"></el-empty>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
// 在文件顶部添加类型声明
declare global {
  interface Window {
    _tempFeatures: __esri.Graphic[]
  }
}
import { ref, onMounted, watch, reactive } from 'vue'
import { Plus, Edit, Delete, Check, Close, Search, Back } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import { useRouter, useRoute } from 'vue-router'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import Point from '@arcgis/core/geometry/Point'
import Polygon from '@arcgis/core/geometry/Polygon'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import SimpleFillSymbol from '@arcgis/core/symbols/SimpleFillSymbol'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'
import { gaodeLayer } from '@/utils/GaoDeBaseLayer'

// 检查用户权限
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()

// 如果不是管理员，重定向到首页
if (!userStore.isAdmin) {
  ElMessage.warning('您没有权限访问该页面')
  router.push('/')
}

// 地图和图层
let view: __esri.MapView
let featureLayers: __esri.FeatureLayer[] = []
let primaryFeatureLayer: __esri.FeatureLayer
let sketchViewModel: __esri.SketchViewModel
let graphicsLayer: __esri.GraphicsLayer
let newPolygonGeometry: Polygon | null = null

// 状态变量
const loading = ref(true)
const searchQuery = ref('')
const tableData = ref<any[]>([])
const selectedFeatureId = ref<number | null>(null)
const selectedFeatureName = ref('')
const selectedFeatureType = ref('')
const isAddingMode = ref(false)
const showFormDrawer = ref(false)
const showDetailsDrawer = ref(false)
const isEditing = ref(false)
const currentFeature = ref<any>(null) // 存储提取的属性数据，不存储ESRI对象
const formRef = ref<FormInstance>()

// 当前选中的景区
const activeArea = ref('erdihu') // 默认胶南灵山岛保护区

// 各个景区的中心坐标
const areaCenters = {
  erdihu: [120.179558,35.765965], // 胶南灵山岛坐标
  yunmen: [120.503415,35.967122], // 大公岛坐标
  bailang: [120.022251,37.00615], // 大泽山坐标
  xiashan: [120.605305,36.198964], // 崂山坐标
  binhai: [119.93718,36.121442], // 胶州艾山坐标
  mihe: [120.651138,36.340289] // 马山坐标
}

// 表单数据
const formData = reactive({
  Name: '',
  AreaType: '',
  Description: '',
  Status: '',
  PhotoBase64: '',
  OwnerArea: '',
  Price: '',
  MaintanceDataJson: '',
})

// 从要素中提取属性数据
const extractFeatureData = (feature: any) => {
  if (!feature || !feature.attributes) return null

  return {
    attributes: { ...feature.attributes },
    // 存储坐标信息，但不存储完整的geometry对象
    geometryInfo: feature.geometry
      ? {
          x: feature.geometry.x,
          y: feature.geometry.y,
          type: feature.geometry.type,
        }
      : null,
  }
}

// 根据类型获取标签类型
const getTypeTagType = (type: string) => {
  switch (type) {
    case '保护区浏览区':
      return 'success'
    case '缓冲区':
      return 'danger'
    case '自然保护区':
      return 'primary'
    default:
      return 'info'
  }
}

// 根据状态获取标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case '正常开放':
      return 'success'
    case '维护中':
      return 'warning'
    case '暂停开放':
      return 'danger'
    default:
      return 'info'
  }
}

// 查询保护区数据
const queryFeatures = async () => {
  if (!featureLayers || featureLayers.length === 0) return

  loading.value = true
  try {
    const allQueryResults: any[] = []
    const allOriginalFeatures: __esri.Graphic[] = []

    // 根据当前选中的景区过滤
    const currentAreaName = getCurrentAreaName()
    let whereClause = `OwnerArea='${currentAreaName}' OR OwnerArea IS NULL`

    // 如果有搜索条件，添加到查询中
    if (searchQuery.value) {
      whereClause += ` AND Name LIKE '%${searchQuery.value}%'`
    }

    // 依次查询三个图层
    for (let i = 0; i < featureLayers.length; i++) {
      const layer = featureLayers[i]
      const query = layer.createQuery()
      query.where = whereClause
      query.outFields = ['*']

      try {
        const result = await layer.queryFeatures(query)

        // 为每个要素添加图层类型和索引信息
        const layerType = i === 0 ? 'hexin' : i === 1 ? 'huanchong' : 'shiyan'
        const processedFeatures = result.features.map((feature, featureIndex) => {
          // 存储原始要素
          allOriginalFeatures.push(feature)

          return {
            _index: allQueryResults.length + featureIndex,
            _layerIndex: i,
            _layerType: layerType,
            attributes: { ...feature.attributes },
          }
        })

        allQueryResults.push(...processedFeatures)
      } catch (layerError) {
        console.error(`查询图层 ${i} 失败:`, layerError)
      }
    }

    // 存储原始的ESRI要素对象到非响应式变量中
    window._tempFeatures = allOriginalFeatures

    // 将要素ID和属性数据存储到响应式变量中
    tableData.value = allQueryResults
  } catch (error) {
    console.error('查询保护区数据失败', error)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 监听搜索条件变化
watch(searchQuery, () => {
  queryFeatures()
})

// 初始化地图
const initMap = async () => {
  // 创建地图实例
  const map = new Map({
    basemap: 'streets-vector',
  })

  // 创建地图视图
  view = new MapView({
    container: 'scenicMapView',
    map: map,
    center: areaCenters[activeArea.value as keyof typeof areaCenters], // 根据当前选中的景区设置中心点
    zoom: 15,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 创建保护区要素图层
  const featureLayerHe = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/hexinFeaturelayer/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-fill',
        color: [225, 76, 66, 0.5], // 红色
        outline: {
          width: 0.5,
          color: 'white',
        },
      },
    },
  })
  const featureLayerHu = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/huanchong/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-fill',
        color: [0, 112, 255, 0.5], // 蓝色
        outline: {
          width: 0.5,
          color: 'white',
        },
      },
    },
  })
  const featureLayerS = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/shiyan/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-fill',
        color: [56, 168, 0, 0.5], // 绿色
        outline: {
          width: 0.5,
          color: 'white',
        },
      },
    },
  })

  // 将三个图层存储到数组中用于查询
  featureLayers = [featureLayerHe, featureLayerHu, featureLayerS]
  // 设置主要图层用于编辑操作（使用第一个图层作为主要编辑图层）
  primaryFeatureLayer = featureLayerHe

  // 创建图形图层用于绘制
  graphicsLayer = new GraphicsLayer()
  map.add(graphicsLayer)

  // 将要素图层添加到地图
  map.add(featureLayerHe)
  map.add(featureLayerHu)
  map.add(featureLayerS)

  // 创建SketchViewModel用于绘制面要素
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: graphicsLayer,
    polygonSymbol: {
      type: 'simple-fill',
      color: [0, 122, 194, 0.3],
      outline: {
        color: [0, 122, 194],
        width: 2,
      },
    },
  })

  // 监听绘制完成事件
  sketchViewModel.on('create', (event) => {
    if (event.state === 'complete') {
      newPolygonGeometry = event.graphic.geometry as Polygon
      // 打开创建表单
      isAddingMode.value = false
      isEditing.value = false
      currentFeature.value = null
      resetForm()
      formData.OwnerArea = getCurrentAreaName()
      showFormDrawer.value = true

      // 还原鼠标样式
      if (view?.container) {
        ;(view.container as HTMLElement).style.cursor = 'default'
      }
    }
  })

  // 添加点击事件监听器以选择要素
  view.on('click', async (event) => {
    if (isAddingMode.value) {
      return // 绘制模式下不处理点击选择
    }

    const hitResults = (await view?.hitTest(event))?.results as __esri.MapViewGraphicHit[]
    const feature = hitResults.find((result) =>
      featureLayers.some(layer => result.layer?.id === layer?.id)
    )?.graphic

    if (feature) {
      selectedFeatureId.value = feature.attributes.FID
      selectedFeatureName.value =
        feature.attributes.Name || `保护区 #${selectedFeatureId.value}`
      selectedFeatureType.value = feature.attributes.AreaType || ''

      // 添加高亮效果
      view?.graphics.removeAll()
      const highlightSymbol = new SimpleFillSymbol({
        color: [255, 255, 255, 0.3],
        outline: {
          color: [0, 122, 194],
          width: 3,
        },
      })

      const highlightGraphic = new Graphic({
        geometry: feature.geometry,
        symbol: highlightSymbol,
      })

      view?.graphics.add(highlightGraphic)
    } else {
      selectedFeatureId.value = null
      selectedFeatureName.value = ''
      selectedFeatureType.value = ''
      view?.graphics.removeAll()
    }
  })

  // 加载要素数据
  await loadFeatures()
}

// 加载要素数据
const loadFeatures = async () => {
  await queryFeatures()
}

// 获取当前景区名称
const getCurrentAreaName = () => {
  switch (activeArea.value) {
    case 'erdihu':
      return '胶南灵山岛保护区'
    case 'yunmen':
      return '大公岛保护区'
    case 'bailang':
      return '大泽山保护区'
    case 'xiashan':
      return '崂山保护区'
    case 'binhai':
      return '胶州艾山保护区'
    case 'mihe':
      return '马山保护区'
    default:
      return ''
  }
}

// 处理景区切换
const handleAreaChange = () => {
  // 将地图中心移动到选中的景区
  view?.goTo({
    center: areaCenters[activeArea.value as keyof typeof areaCenters],
    zoom: 15,
  })

  // 重新加载数据
  loadFeatures()
}

// 启动添加模式
const startAddingMode = () => {
  isAddingMode.value = true

  // 清除之前的图形
  graphicsLayer?.removeAll()

  // 开始绘制面要素
  if (sketchViewModel) {
    sketchViewModel.create('polygon')
  }

  // 更改鼠标样式
  if (view?.container) {
    ;(view.container as HTMLElement).style.cursor = 'crosshair'
  }
}

// 取消添加模式
const cancelAddingMode = () => {
  isAddingMode.value = false
  newPolygonGeometry = null

  // 取消当前绘制操作
  if (sketchViewModel) {
    sketchViewModel.cancel()
  }

  // 清除图形
  graphicsLayer?.removeAll()

  // 还原鼠标样式
  if (view?.container) {
    ;(view.container as HTMLElement).style.cursor = 'default'
  }

  view?.graphics.removeAll()
}

// 打开编辑表单
const openEditForm = () => {
  if (!selectedFeatureId.value) {
    ElMessage.warning('请先选择一个保护区')
    return
  }

  isEditing.value = true
  loadFeatureDetails(selectedFeatureId.value)
}

// 加载要素详情
const loadFeatureDetails = async (featureId: number) => {
  try {
    // 查询选中的要素
    if (!featureLayers || featureLayers.length === 0) {
      ElMessage.error('图层未初始化')
      return
    }

    // 在所有图层中查找要素
    let foundFeature = null
    for (const layer of featureLayers) {
      const query = layer.createQuery()
      query.where = `FID = ${featureId}`
      query.outFields = ['*']

      try {
        const result = await layer.queryFeatures(query)
        if (result.features.length > 0) {
          foundFeature = result.features[0]
          break
        }
      } catch (layerError) {
        console.error('查询图层失败:', layerError)
      }
    }

    if (foundFeature) {
      currentFeature.value = extractFeatureData(foundFeature)
      // 填充表单数据
      resetForm()
      Object.keys(formData).forEach((key) => {
        if (foundFeature.attributes[key] !== undefined) {
          // @ts-ignore
          formData[key] = foundFeature.attributes[key]
        }
      })

      // 检查照片数据
      console.log('加载的照片数据:', formData.PhotoBase64)

      showFormDrawer.value = true
    }
  } catch (error) {
    console.error('加载保护区详情失败', error)
    ElMessage.error('加载保护区详情失败')
  }
}

// 删除要素
const deleteFeature = async () => {
  if (!selectedFeatureId.value) {
    ElMessage.warning('请先选择一个保护区')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除保护区 "${selectedFeatureName.value}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 先查询要素详情，确保我们有完整的数据
    let targetLayer = null
    let feature = null

    // 在所有图层中查找要素
    for (const layer of featureLayers) {
      const query = layer.createQuery()
      query.where = `FID = ${selectedFeatureId.value}`
      query.outFields = ['*']

      try {
        const result = await layer.queryFeatures(query)
        if (result.features.length > 0) {
          targetLayer = layer
          feature = result.features[0]
          break
        }
      } catch (layerError) {
        console.error('查询图层失败:', layerError)
      }
    }

    if (feature && targetLayer) {
      // 如果有照片，先清空照片数据
      if (feature.attributes.PhotoBase64) {
        console.log('删除前清空照片数据')
        const updateFeature = new Graphic({
          attributes: {
            FID: selectedFeatureId.value,
            PhotoBase64: '', // 使用空字符串而不是 null
          },
        })

        // 先更新清空照片
        const updateResult = await targetLayer.applyEdits({
          updateFeatures: [updateFeature],
        })

        console.log('清空照片结果:', updateResult)

        // 等待一下，确保更新完成
        await new Promise((resolve) => setTimeout(resolve, 1000))
      }

      // 然后删除要素
      const deleteFeature = new Graphic({
        attributes: {
          FID: selectedFeatureId.value,
        },
      })

      await targetLayer?.applyEdits({
        deleteFeatures: [deleteFeature],
      })
    }

    ElMessage.success('保护区已删除')
    selectedFeatureId.value = null
    selectedFeatureName.value = ''
    selectedFeatureType.value = ''
    view?.graphics.removeAll()

    // 重新加载数据
    await loadFeatures()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除保护区失败', error)
      ElMessage.error('删除保护区失败')
    }
  }
}

// 查看要素详情
const viewFeatureDetails = (row: any) => {
  // 从非响应式存储中获取原始要素
  const originalFeature = window._tempFeatures?.[row._index]

  // 提取属性数据
  currentFeature.value = extractFeatureData(originalFeature)
  showDetailsDrawer.value = true

  // 在地图上高亮显示
  highlightFeatureOnMap(originalFeature)
}

// 编辑要素
const editFeature = (row: any) => {
  console.log('编辑要素:', row)

  // 如果是从详情页面传递过来的 currentFeature
  if (row && row.attributes && row.attributes.FID && !row._index) {
    // 直接使用传递过来的对象
    selectedFeatureId.value = row.attributes.FID
    isEditing.value = true

    // 填充表单数据
    resetForm()
    Object.keys(formData).forEach((key) => {
      if (row.attributes[key] !== undefined) {
        // @ts-ignore
        formData[key] = row.attributes[key]
      }
    })

    console.log('从详情页面编辑，表单数据:', formData)
    showFormDrawer.value = true

    // 如果有几何信息，在地图上高亮显示
    if (row.geometryInfo) {
      // 创建一个点几何对象
      const point = new Point({
        x: row.geometryInfo.x,
        y: row.geometryInfo.y,
        spatialReference: view?.spatialReference,
      })

      // 清除之前的高亮
      view?.graphics.removeAll()

      // 创建高亮符号
      const highlightSymbol = new SimpleMarkerSymbol({
        color: [255, 255, 255, 0.8],
        size: 16,
        outline: {
          color: [0, 122, 194],
          width: 3,
        },
      })

      // 创建高亮图形
      const highlightGraphic = new Graphic({
        geometry: point,
        symbol: highlightSymbol,
      })

      // 添加到地图
      view?.graphics.add(highlightGraphic)

      // 将视图中心移动到要素位置
      view?.goTo({
        target: point,
        zoom: 15,
      })
    }
  } else {
    // 从非响应式存储中获取原始要素
    const originalFeature = window._tempFeatures?.[row._index]

    // 提取属性数据
    currentFeature.value = extractFeatureData(originalFeature)
    isEditing.value = true
    showFormDrawer.value = true

    // 填充表单数据
    resetForm()
    Object.keys(formData).forEach((key) => {
      if (originalFeature.attributes[key] !== undefined) {
        // @ts-ignore
        formData[key] = originalFeature.attributes[key]
      }
    })

    console.log('从列表编辑，表单数据:', formData)

    // 在地图上高亮显示
    highlightFeatureOnMap(originalFeature)
  }
}

// 在地图上高亮显示要素
const highlightFeatureOnMap = (feature: any) => {
  if (!feature || !feature.geometry) return

  // 清除之前的高亮
  view?.graphics.removeAll()

  // 创建高亮符号（面要素）
  const highlightSymbol = new SimpleFillSymbol({
    color: [255, 255, 255, 0.3],
    outline: {
      color: [0, 122, 194],
      width: 3,
    },
  })

  // 创建高亮图形
  const highlightGraphic = new Graphic({
    geometry: feature.geometry,
    symbol: highlightSymbol,
  })

  // 添加到地图
  view?.graphics.add(highlightGraphic)

  // 将视图中心移动到要素位置
  view?.goTo({
    target: feature.geometry,
    zoom: 15,
  })

  // 更新选中状态
  selectedFeatureId.value = feature.attributes.FID
  selectedFeatureName.value = feature.attributes.Name || `保护区 #${selectedFeatureId.value}`
  selectedFeatureType.value = feature.attributes.AreaType || ''
}

// 处理表格行点击
const handleRowClick = (row: any) => {
  // 从非响应式存储中获取原始要素
  const originalFeature = window._tempFeatures?.[row._index]
  highlightFeatureOnMap(originalFeature)
}

// 重置表单
const resetForm = () => {
  formData.Name = ''
  formData.AreaType = ''
  formData.Description = ''
  formData.Status = ''
  formData.PhotoBase64 = ''
  formData.OwnerArea = ''
  formData.Price = ''
  formData.MaintanceDataJson = ''
}

// 处理图片变化
const handlePhotoChange = (file: any) => {
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    formData.PhotoBase64 = reader.result as string
  }
}

// 处理图片删除
const handlePhotoRemove = () => {
  // 清空 PhotoBase64 字段
  formData.PhotoBase64 = ''
  console.log('照片已删除，PhotoBase64 已清空')
}

// 关闭表单
const handleFormClose = () => {
  showFormDrawer.value = false
  resetForm()
}

// 保存要素
const saveFeature = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写必填字段')
      return
    }

    try {
      if (!primaryFeatureLayer) {
        ElMessage.error('图层未初始化')
        return
      }

      // 准备属性数据
      const attributes = { ...formData }

      // 确保设置了所属区域
      if (!attributes.OwnerArea) {
        attributes.OwnerArea = getCurrentAreaName()
      }

      // 如果照片字段为空字符串，则设置为空
      if (attributes.PhotoBase64 === '') {
        attributes.PhotoBase64 = ''
      }

      // 如果维护数据为空，设置为空字符串
      if (!attributes.MaintanceDataJson) {
        attributes.MaintanceDataJson = ''
      }

      console.log('保存前的属性数据:', attributes)

      if (isEditing.value && selectedFeatureId.value) {
        // 更新现有要素
        const updateFeature = new Graphic({
          attributes: {
            FID: selectedFeatureId.value,
            ...attributes,
          },
        })
        console.log(updateFeature.attributes)
        // 查找要素所在的图层进行更新
        let targetLayer = primaryFeatureLayer
        if (selectedFeatureId.value) {
          for (const layer of featureLayers) {
            const query = layer.createQuery()
            query.where = `FID = ${selectedFeatureId.value}`
            query.outFields = ['FID']

            try {
              const result = await layer.queryFeatures(query)
              if (result.features.length > 0) {
                targetLayer = layer
                break
              }
            } catch (layerError) {
              console.error('查询图层失败:', layerError)
            }
          }
        }

        const result = await targetLayer.applyEdits({
          updateFeatures: [updateFeature],
        })

        if (result.updateFeatureResults.length > 0) {
          ElMessage.success('保护区已更新')
          showFormDrawer.value = false
          await loadFeatures()
        } else {
          ElMessage.error('更新保护区失败')
        }
      } else {
        // 创建新要素
        if (!newPolygonGeometry) {
          ElMessage.warning('无法获取保护区边界')
          return
        }

        const graphic = new Graphic({
          geometry: newPolygonGeometry,
          attributes: attributes,
        })

        const result = await primaryFeatureLayer.applyEdits({
          addFeatures: [graphic],
        })

        if (result.addFeatureResults.length > 0) {
          ElMessage.success('保护区已添加')
          showFormDrawer.value = false
          newPolygonGeometry = null
          // 清除绘制图形
          graphicsLayer?.removeAll()
          await loadFeatures()
        } else {
          ElMessage.error('添加保护区失败')
        }
      }
    } catch (error) {
      console.error('保存保护区失败', error)
      ElMessage.error('保存保护区失败')
    }
  })
}

// 返回首页
const goBack = () => {
  router.push('/')
}

// 页面加载完成后初始化地图
onMounted(() => {
  initMap()
})
</script>

<style scoped lang="scss">
.scenic-management-container {
  padding: 20px;
}

.scenic-management-header {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-left: 4px solid #409eff;
}

.header-actions {
  margin-bottom: 15px;
}

.scenic-management-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.scenic-management-header p {
  color: #606266;
  font-size: 14px;
}

.map-container {
  height: 500px;
  width: 100%;
  position: relative;
}

.map-card,
.action-card,
.feature-list-card,
.area-select-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 200px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.selected-feature-info {
  background-color: #f0f9eb;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border-left: 4px solid #67c23a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.selected-feature-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #303133;
}

.selected-feature-info p {
  margin: 5px 0;
  color: #606266;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 10px;
}

.feature-form {
  padding: 20px;
}

.existing-photo {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 10px;
  background-color: #f8f8f8;
}

.remove-photo-btn {
  margin-top: 10px;
}

/* 详情页样式 */
.feature-details {
  padding: 20px;
}

.details-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.no-feature-selected {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 状态指示器 */
.status-indicator {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.pulse-dot {
  width: 10px;
  height: 10px;
  background-color: #f56c6c;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.2);
    opacity: 1;
  }
  100% {
    transform: scale(0.8);
    opacity: 0.8;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .scenic-management-container {
    padding: 10px;
  }

  .map-container {
    height: 350px;
  }

  .search-input {
    width: 150px;
  }
}
</style>
